package com.yxsk.relay.job.component.endpoint.async;

import com.yxsk.relay.job.component.common.protocol.message.execute.JobExecuteRequest;
import com.yxsk.relay.job.component.common.thread.observe.Observable;
import com.yxsk.relay.job.component.common.thread.Task;
import com.yxsk.relay.job.component.endpoint.handle.JobExecutor;
import lombok.Builder;

/**
 * @Author 11376
 * @CreaTime 2019/6/19 15:23
 * @Description
 */
@Builder
public class AsyncTask<T> extends RelayJobAsyncWorker<String> implements Observable, Task<String> {

    private JobExecutor jobExecutor;
    private JobExecuteRequest request;
    private ExecuteCallback callback;

    // 执行结果
    private String result;
    // 执行的异常信息
    private Exception error;

    private Cycle cycle = Cycle.NEW;

    public String getResult() {
        return result;
    }

    public Exception getError() {
        return error;
    }

    @Override
    protected String work() {
        this.cycle = Cycle.STARTED;
        try {
            this.cycle = Cycle.RUNNING;
            this.result = this.jobExecutor.execute(request.getParam());
            this.cycle = Cycle.FINISH;
            if (this.callback != null) {
                callback.callback(this.request, result);
            }
            return result;
        } catch (Exception e) {
            this.cycle = Cycle.ERROR;
            this.error = e;
            if (this.callback != null) {
                callback.onError(this.request, e);
            }
        }
        return null;
    }

    @Override
    public Cycle getCycle() {
        return this.cycle;
    }

    @Override
    public Task getTask() {
        return this;
    }

    @Override
    public String execute() {
        return this.work();
    }

    public interface ExecuteCallback {

        void callback(JobExecuteRequest request, String result);

        void onError(JobExecuteRequest request, Throwable e);

    }

}
